<?php
require_once(FQ_THIRDPARTY.'/adodb5/adodb.inc.php');
require_once(FQ_THIRDPARTY.'/dwoo/dwooAutoload.php');

class TemplateEngine_base extends Flexqueries_base
{
	protected $templatePrefix;
	protected $dwoo;
	
	public function __construct()
	{
		parent::__construct();
		
		$this->templatePrefix = FQ_ROOT."/templates/".$_REQUEST['module']."/".$_REQUEST['action'].".tpl";
		$this->templatePrefix = realpath($this->templatePrefix);
		$this->dwoo = new Dwoo();
		
	}
	
	public function generatePage($data = array())
	{
		$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
		$this->injectStandardVariables($data);
		$output .= $this->dwoo->get($this->templatePrefix, $data);
		
		return $output;
	}
	
	protected function injectStandardVariables(&$data)
	{
		$data['www'] = $this->getWwwDir();
		$data['session'] = SessionManager::$instance;
		$data['url'] = $_SERVER['REQUEST_URI'];
		$data['fc'] = $this->getWwwDir()."/fc.php";
		$data['back'] = $_SERVER['HTTP_REFERER'];
	} 
	
	public function generatePageWithTemplate($templateFile, $data = array())
	{
		$this->templatePrefix = FQ_ROOT."/templates/".$_REQUEST['module']."/".$templateFile.".tpl";
		$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
		$this->injectStandardVariables($data);
		$output .= $this->dwoo->get($this->templatePrefix, $data);
		
		return $output;
	}
	
	public function setTemplate($templateFile)
	{
		$this->templatePrefix = FQ_ROOT."/templates/".$_REQUEST['module']."/".$templateFile.".tpl";
	}
	
	public function setModuleAndTemplate($module, $templateFile)
	{
		$this->templatePrefix = FQ_ROOT."/templates/".$module."/".$templateFile.".tpl";
	}
	
	public function generatePageWithModuleAndTemplate($module, $templateFile, $data = array())
	{
		$this->templatePrefix = FQ_ROOT."/templates/".$module."/".$templateFile.".tpl";
		$output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
		$this->injectStandardVariables($data);
		$output .= $this->dwoo->get($this->templatePrefix, $data);
		
		return $output;
	}
	
	public function getWwwDir()
	{
		$localWwwDir = substr(FQ_WWW, strlen($_SERVER['DOCUMENT_ROOT']));
		$localWwwDir = str_replace("\\", "/", $localWwwDir);
		return $localWwwDir;
	}
	
	/**
	 * Default implementation
	 */
	public function home_action()
	{
		return $this->generatePage();
	}
	
	protected function redirect($module, $method)
	{
		$url = $this->getWwwDir()."/$module-$method";
		header("Location: $url");
	}
	
	public static function generateMessage($message = "")
	{
		$te = new TemplateEngine_base();
		return $te->generatePageWithModuleAndTemplate('tools', 'message', array('message'=>$message));
	}
	
}

?>